package com.yaolaizaixian.merchant.order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.CreadOrderModel;
import com.yaolaizaixian.merchant.bean.OrderLsfp;
import com.yaolaizaixian.merchant.bean.OrderLsm;
import com.yaolaizaixian.merchant.home.CancelOrderActivity;
import com.yaolaizaixian.merchant.home.ConfirmActivity;
import com.yaolaizaixian.merchant.home.OrderSuccessActivity;
import com.yaolaizaixian.merchant.utils.AppManager;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 支付二维码界面
 */
public class PayCodeActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.tv_saoyisao)
    TextView tvSaoyisao;
    @BindView(R.id.tv_weixin)
    TextView tvWeixin;
    @BindView(R.id.iv_paycode)
    ImageView ivPaycode;
    @BindView(R.id.tv_tishi)
    TextView tvTishi;
    @BindView(R.id.bt_quxiao)
    Button btQuxiao;
    //标记是否在当前页
    public static boolean isForeground = false;
    private String TAG = "PayCodeActivity";
    public static String mysysno="";
    private String money;
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {

                        CreadOrderModel creadOrderModel = GsonUtil.jsonToBean(result, CreadOrderModel.class);
                        OrderLsm orderLsm = creadOrderModel.getData().getLsm();
                        OrderLsfp lsfp = creadOrderModel.getData().getLsfp();
                        //订单id
                        String sysno = orderLsm.getSysno();
//                        lsm.status	string	订单状态 5：待确定，10：待付款，15已付款，-100：取消
                        String status = orderLsm.getStatus();
//                        lsfp.payStatus	String	支付状态：10待支付，20已支付，-90取消支付
                        String payStatus = lsfp.getPayStatus();
                        //待确定
                        if ("5".equals(status)){

                            Toasty.success(PayCodeActivity.this, "该订单未收到用户确认！", Toast.LENGTH_SHORT, true).show();

                        }
                        //待付款
                        //线下支付 跳转订单确认页 否则不跳转
                        else if ("10".equals(status)){

                            if ("168".equals(lsfp.getPayTypeSysno())){
                             //线上
                                Toasty.error(PayCodeActivity.this, "该订单未完成支付！", Toast.LENGTH_SHORT, true).show();
                            }
                            else {

                                Intent intent1 = new Intent(PayCodeActivity.this, ConfirmActivity.class);
                                intent1.putExtra("sysno", sysno);
                                startActivity(intent1);
                                finish();
                                if ("1".equals(sign)){
                                    SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", true);
                                }

                            }

                        }
                        //已付款 补录页面
                        else if (Integer.parseInt(status)>=15){
                            SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", true);
                                                        //未补录
                            if ("0".equals(creadOrderModel.getData().getIsDitional())) {

                                Intent intent = new Intent(PayCodeActivity.this, OrderSuccessActivity.class);
                                intent.putExtra("sysno", sysno);
                                startActivity(intent);
                                finish();
                                if ("1".equals(sign)){
                                    SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", true);
                                }

                            }
                            //已补录
                            else if ("1".equals(creadOrderModel.getData().getIsDitional())) {

                                Toasty.success(PayCodeActivity.this, "该订单已完成！", Toast.LENGTH_SHORT, true).show();
                                finish();
                                AppManager.getAppManager().finishAllActivity();
                            }
                        }
                        //已取消 订单取消页
                        else if ("-100".equals(status)){


                            Intent intent = new Intent(PayCodeActivity.this, CancelOrderActivity.class);
                            intent.putExtra("sysno", sysno);
                            startActivity(intent);
                            finish();
                            if ("1".equals(sign)){
                                SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", true);
                            }
                        }
//
//                        Intent intent = new Intent(PayCodeActivity.this, CancelOrderActivity.class);
//                        intent.putExtra("sysno", sysno);
//                        startActivity(intent);

                    } else {

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {

                            showConflictDialog(PayCodeActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(PayCodeActivity.this, "您的账号在其它设备登录");

                        } else {

                            Toast.makeText(PayCodeActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT).show();

                            return;
                        }
                    }

                    break;

            }
        }
    };
    private String sign;


    @Override
    public void initView() {

        setContentView(R.layout.activity_order_paycode);
    }

    @Override
    public void initData() {

        tvTitleText.setText("收单页");

        //字体 加粗
        TextPaint tp = tvSaoyisao.getPaint();
        tp.setFakeBoldText(true);
        mysysno="";
        //订单id
        mysysno = getIntent().getStringExtra("sysno");
        LogUtil.e(TAG,"mysysno1==========="+mysysno);
        //订单金额
        money = getIntent().getStringExtra("money");
        sign = getIntent().getStringExtra("sign");
        //订单金额创建二维码
        createErweima(mysysno);
        registerMessageReceiver();

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        AppManager.getAppManager().addActivity(this);
    }
    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }


    @Override
    protected void onPause() {
        isForeground = false;

        super.onPause();
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
        //当页面关闭时，关闭广播
        unregisterReceiver(mMessageReceiver);
    }

    //创建二维码
    private void createErweima(final String url) {

        String allurl=BaseInfo.UserH5+"orderConfirm?lifeOrderId="+url;
        LogUtil.e(TAG,allurl);
        Bitmap mBitmap = CodeUtils.createImage(allurl, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.icon));
        ivPaycode.setImageBitmap(mBitmap);

    }
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                  //透传内容
                String messge = intent.getStringExtra(KEY_MESSAGE);
                setCostomMsg(messge);
            }
        }
    }

    private void setCostomMsg(String msg)  {

        JSONObject myJsonObject = null;

        Log.e(TAG,"推送数据"+msg);

        try {

            //获取data
            myJsonObject = new JSONObject(msg);
            String data= myJsonObject.getString("data");

            //获取sysno
            myJsonObject = new JSONObject(data);
            String sysno=myJsonObject.getString("sysno");

            LogUtil.e(TAG,"推送id"+sysno);

            LogUtil.e(TAG,"当前id"+mysysno);

            //判断id是否相等，等服务器调通，将这个方法打开
            if (!TextUtils.isEmpty(sysno)&&mysysno.equals(sysno)){

                //刷新跳转
                getData(sysno);

            }

        } catch (JSONException e) {

            e.printStackTrace();
            LogUtil.e(TAG,e.toString());
        }
    }

    @OnClick({R.id.ll_back, R.id.bt_quxiao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:

                finish();

                break;

            //刷新跳转 请求接口
            case R.id.bt_quxiao:

                getData(mysysno);
                LogUtil.e(TAG, "mysysno2===========" + mysysno);

                break;
        }
    }
    //订单详情
    private void getData(String sysno) {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();

            final String url = BaseInfo.URL + "lifeOrderController/lifeOrderInfo.do";
            // sysNo 值  3des加密
            //订单id
            sortedParams.put("lifeOrderSysno", sysno);
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, this))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            Toasty.error(PayCodeActivity.this, "请检查网络", Toast.LENGTH_SHORT, true).show();
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }

    public  String getSysno()
    {
        return  mysysno;
    }

}
